/**
 * *********************************************************
 * Sensors platform by PoLuX
 * *********************************************************
 */

/**
 * Libraries
 */
#include "Wire.h"
#include "Arduino_Sensors.h"
#include "DHT.h"
#include "BMP085.h"

/**
 * Setup of Arduino's PIN
 */
#define PIN_ANALOG_LUM 0			// Analog PIN for Photo resistor
#define DHT_DIGITAL_PIN 7     		// Digital PIN for DHT22

#define DHT_DIGITAL_TYPE DHT22   	// DHT 22  (AM2302)

DHT dht(DHT_DIGITAL_PIN, DHT_DIGITAL_TYPE);
BMP085 dps = BMP085();

/* Format Reports for messaging with Raspberry */
void formatReport(float temp, long pres,  float hum,  long lum, char * report)
{
	// Locals variables
    char valtemp[10];
    char valpres[10];
    char valhum[10];

    // Format all decimals values in buffer(char)
    dtostrf(temp, 3, 2, valtemp);
    dtostrf(pres, 3, 2, valpres);
    dtostrf(hum, 3, 2, valhum);

    // Build response
    sprintf(report,"T=%s|P=%s|H=%s|L=%d",valtemp,valpres,valhum,(int)lum);
}

/* Send launching message about reports */
void sendReport(float temp, long pres,  float hum,  long lum)
{
    char reportContent[50];
    formatReport(temp,pres,hum,lum,reportContent);
    Serial.write(reportContent);
}

/**
 * Initialization
 */
void setup()
{
	Serial.begin(9600);
	dht.begin();
	Wire.begin();
	dps.init();
	dumpRegisters();
	dps.dumpCalData();
}

/**

/**
 * Main Procedure
 */
void loop()
{
	// Locals
	int32_t pres = 0;
	int lum;
	float hum;
	float temp;

	// Getting data from sensors
	/* TODO Gestion des erreurs => isnan(vars) */
	dps.getPressure(&pres);
	lum = analogRead(PIN_ANALOG_LUM);
	hum = dht.readHumidity();
	temp = dht.readTemperature();

	// Sending Reports
	sendReport(temp,pres,hum,lum);
	delay(60000);
}



void dumpRegisters() {
  byte ValidRegisterAddr[]={0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF,0xF6,0xF7,0xF8,0xF9};
  byte _b, i, totregisters = sizeof(ValidRegisterAddr);
  Serial.println("---dump start---");
  Serial.println("Register address|Register data");
  Serial.println("Reg.address(hex,dec) Reg.data(bin,hex,dec)");
  for (i=0;i<totregisters;i++){
    Serial.print("0x");
    Serial.print(ValidRegisterAddr[i], HEX);
    Serial.print(",");
    Serial.print(ValidRegisterAddr[i], DEC);
    Serial.print(",");
    dps.readmem(ValidRegisterAddr[i], 1, &_b);
    Serial.print("b");
    print_bits(_b);
    Serial.print(",0x");
    Serial.print(_b,HEX);
    Serial.print(",");
    Serial.println(_b,DEC);
  }
  Serial.println("---dump end---");
}

void print_bits(byte val){
  int i;
  for(i=7; i>=0; i--)
    Serial.print(val >> i & 1, BIN);
}











